<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- 
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License. 
-->
<html>
<head>
    <link type="text/css" rel="stylesheet" href="https://struts.apache.org/css/default.css">
    <style type="text/css">
        .dp-highlighter {
            width:95% !important;
        }
    </style>
    <style type="text/css">
        .footer {
            background-image:      url('https://cwiki.apache.org/confluence/images/border/border_bottom.gif');
            background-repeat:     repeat-x;
            background-position:   left top;
            padding-top:           4px;
            color:                 #666;
        }
    </style>
    <link href='https://struts.apache.org/highlighter/style/shCoreStruts.css' rel='stylesheet' type='text/css' />
    <link href='https://struts.apache.org/highlighter/style/shThemeStruts.css' rel='stylesheet' type='text/css' />
    <script src='https://struts.apache.org/highlighter/js/shCore.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushPlain.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushXml.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushJava.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushJScript.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushGroovy.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushBash.js' type='text/javascript'></script>
    <script type="text/javascript">
        SyntaxHighlighter.defaults['toolbar'] = false;
        SyntaxHighlighter.all();
    </script>
    <script type="text/javascript" language="javascript">
        var hide = null;
        var show = null;
        var children = null;

        function init() {
            /* Search form initialization */
            var form = document.forms['search'];
            if (form != null) {
                form.elements['domains'].value = location.hostname;
                form.elements['sitesearch'].value = location.hostname;
            }

            /* Children initialization */
            hide = document.getElementById('hide');
            show = document.getElementById('show');
            children = document.all != null ?
                    document.all['children'] :
                    document.getElementById('children');
            if (children != null) {
                children.style.display = 'none';
                show.style.display = 'inline';
                hide.style.display = 'none';
            }
        }

        function showChildren() {
            children.style.display = 'block';
            show.style.display = 'none';
            hide.style.display = 'inline';
        }

        function hideChildren() {
            children.style.display = 'none';
            show.style.display = 'inline';
            hide.style.display = 'none';
        }
    </script>
    <title>Introducing Interceptors</title>
</head>
<body onload="init()">
<table border="0" cellpadding="2" cellspacing="0" width="100%">
    <tr class="topBar">
        <td align="left" valign="middle" class="topBarDiv" align="left" nowrap>
            &nbsp;<a href="home.html">Home</a>&nbsp;&gt;&nbsp;<a href="tutorials.html">Tutorials</a>&nbsp;&gt;&nbsp;<a href="getting-started.html">Getting Started</a>&nbsp;&gt;&nbsp;<a href="introducing-interceptors.html">Introducing Interceptors</a>
        </td>
        <td align="right" valign="middle" nowrap>
            <form name="search" action="https://www.google.com/search" method="get">
                <input type="hidden" name="ie" value="UTF-8" />
                <input type="hidden" name="oe" value="UTF-8" />
                <input type="hidden" name="domains" value="" />
                <input type="hidden" name="sitesearch" value="" />
                <input type="text" name="q" maxlength="255" value="" />
                <input type="submit" name="btnG" value="Google Search" />
            </form>
        </td>
    </tr>
</table>

<div id="PageContent">
    <div class="pageheader" style="padding: 6px 0px 0px 0px;">
        <!-- We'll enable this once we figure out how to access (and save) the logo resource -->
        <!--img src="/wiki/images/confluence_logo.gif" style="float: left; margin: 4px 4px 4px 10px;" border="0"-->
        <div style="margin: 0px 10px 0px 10px" class="smalltext">Apache Struts 2 Documentation</div>
        <div style="margin: 0px 10px 8px 10px"  class="pagetitle">Introducing Interceptors</div>

        <div class="greynavbar" align="right" style="padding: 2px 10px; margin: 0px;">
            <a href="https://cwiki.apache.org/confluence/pages/editpage.action?pageId=24187261">
                <img src="https://cwiki.apache.org/confluence/images/icons/notep_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Edit Page"></a>
            <a href="https://cwiki.apache.org/confluence/pages/editpage.action?pageId=24187261">Edit Page</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/listpages.action?key=WW">
                <img src="https://cwiki.apache.org/confluence/images/icons/browse_space.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Browse Space"></a>
            <a href="https://cwiki.apache.org/confluence/pages/listpages.action?key=WW">Browse Space</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/createpage.action?spaceKey=WW&fromPageId=24187261">
                <img src="https://cwiki.apache.org/confluence/images/icons/add_page_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Add Page"></a>
            <a href="https://cwiki.apache.org/confluence/pages/createpage.action?spaceKey=WW&fromPageId=24187261">Add Page</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/createblogpost.action?spaceKey=WW&fromPageId=24187261">
                <img src="https://cwiki.apache.org/confluence/images/icons/add_blogentry_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Add News"></a>
            <a href="https://cwiki.apache.org/confluence/pages/createblogpost.action?spaceKey=WW&fromPageId=24187261">Add News</a>
        </div>
    </div>

    <div class="pagecontent">
        <div class="wiki-content">
            <div id="ConfluenceContent"><div class="confluence-information-macro confluence-information-macro-information"><span class="aui-icon aui-icon-small aui-iconfont-info confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>The example code for this tutorial, interceptors, is available at <a shape="rect" class="external-link" href="https://github.com/apache/struts-examples" rel="nofollow">https://github.com/apache/struts-examples</a></p></div></div><h3 id="IntroducingInterceptors-Introduction">Introduction</h3><p>So far our tutorials have not delved into the inner workings of the Struts 2 framework. But in this tutorial we'll introduce a key set of classes the Struts 2 framework relies upon to do most of the work whenever an Action is executed. In this tutorial's example project there is a register link that is mapped in the Struts XML configuration file (struts.xml) to the execute method of class Register. Before that execute method is called much work is done behind the scenes by the Struts 2 framework. For example:</p><ol><li>Handling any exceptions generated</li><li>Converting the String request parameters to the Register class's instance fields where the name values match</li><li>Calling the validate method and/or the external XML validation</li></ol><p>After the execute method is completed more work must be done</p><ol><li>Handling any exceptions generated</li><li>Converting the Register class's instance fields to String values for display in the view page</li><li>Forwarding to the correct view page depending on the result String returned by the execute method</li></ol><div class="confluence-information-macro confluence-information-macro-note"><span class="aui-icon aui-icon-small aui-iconfont-warning confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>The above list of tasks are not complete - several other tasks are done before and after the execution of the Action.</p></div></div><p>The benefit of using Struts 2 is all this work happens automatically. You can focus on the logic of the controller (the Struts 2 ActionSupport class), the Service layer, the data access layer, your domain models, etc.</p><div class="confluence-information-macro confluence-information-macro-tip"><span class="aui-icon aui-icon-small aui-iconfont-approve confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>The <a shape="rect" class="external-link" href="http://struts.apache.org/mail.html">Struts 2 user mailing list</a> is an excellent place to get help. If you are having a problem getting the tutorial example applications to work search the Struts 2 mailing list. If you don't find an answer to your problem, post a question on the mailing list.</p></div></div><h3 id="IntroducingInterceptors-IntroducingInterceptors">Introducing Interceptors</h3><p>The tasks that are done by the Struts 2 framework before and after an Action is executed are done by Struts 2 interceptors. Interceptors are standard Java classes included in the Struts 2 core jar which are executed in a specific order.</p><p>In our example application there is a package node in struts.xml. The package node has an attribute of extends with a value of "struts-default." The value "struts-default" identifies to the framework the specific stack of interceptors that will be executed before and after the Actions in that package.</p><p>If you want to learn more about the inner workings of interceptors, what interceptors belong to the struts default stack, and what are all the interceptors included with Struts 2, visit <a shape="rect" href="interceptors.html">Understanding Interceptors</a>.</p><p>Sometime the Struts 2 default stack of interceptors are not exactly what you need for a particular action. You may want to use interceptors that are not part of the Struts 2 default stack. For an individual Action or for the entire package of Actions, you can specify a different stack of interceptors that the Action or package should use. Below is how you would specify that the register Action should use both the <a shape="rect" href="logger-interceptor.html">logger</a> and <a shape="rect" href="timer-interceptor.html">timer</a> interceptors in addition to the interceptors provided by the default stack.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>Specify Specific Interceptors For An Action</b></div><div class="codeContent panelContent pdl">
<pre class="brush: xml; gutter: false; theme: Default" style="font-size:12px;">&lt;action name="register" class="org.apache.struts.register.action.Register" method="execute"&gt;
	&lt;interceptor-ref name="timer" /&gt;
	&lt;interceptor-ref name="logger" /&gt;
	&lt;interceptor-ref name="defaultStack"&gt;
		&lt;param name="exception.logEnabled"&gt;true&lt;/param&gt;
		&lt;param name="exception.logLevel"&gt;ERROR&lt;/param&gt;
	&lt;/interceptor-ref&gt;
	&lt;result name="success"&gt;thankyou.jsp&lt;/result&gt;
	&lt;result name="input"&gt;register.jsp&lt;/result&gt;
&lt;/action&gt;

</pre>
</div></div><p>The logger interceptor logs the start and end of the execution of an Action. The timer interceptor logs the amount of time (in milliseconds) for execution of the Action. These two interceptors used together can provide developers useful feedback.</p><p>In the code example above note the three interceptor-ref nodes. Each one has a value for the name attribute. For the register Action we are instructing the framework to use the timer, logger, and defaultStack interceptors. The defaultStack are all the interceptors normally executed for an Action.</p><p>How did I know to use the value of timer for the name attribute and even that there is a timer interceptor? On the <a shape="rect" href="interceptors.html">Interceptors</a> web page in the Struts 2 documentation are a list of interceptors that come with the Struts 2 framework and what the name value is for each interceptor.</p><p>How did I know that the timer interceptor isn't part of the defaultStack of interceptors already? Again on the Interceptors documentation web page is a list of which interceptors belong to the defaultStack.</p><p>Note the param nodes. These nodes are used to provide a value to the setLogEnabled and setLogLevel methods of the <a shape="rect" href="exception-interceptor.html">Exception Interceptor</a>. Providing the values of true and ERROR will cause the Struts 2 framework to log any exceptions not caught by the application's code and to log those exceptions at the ERROR level.</p><h3 id="IntroducingInterceptors-RunTheExample">Run The Example</h3><p>In the example application follow the README instructions to build, deploy, and run the application. View the output sent to the JVM console to see the log messages generated by the logger and timer interceptors. You should see log messages similar to the following:</p><p>INFO: Starting execution stack for action //register<br clear="none"> Nov 20, 2010 9:55:48 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger info</p><p>INFO: Finishing execution stack for action //register</p><p>Nov 20, 2010 9:55:48 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger info</p><p>INFO: Executed action <a shape="rect" class="external-link" href="https://cwiki.apache.org/register!execute">//register!execute</a> took 177 ms.</p><p>If you wanted to have the logger and timer interceptors executed for all Actions in a package you would use the following in struts.xml:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeHeader panelHeader pdl" style="border-bottom-width: 1px;"><b>Specify Specific Interceptors For A Package</b></div><div class="codeContent panelContent pdl">
<pre class="brush: xml; gutter: false; theme: Default" style="font-size:12px;">&lt;package name="basicstruts2" extends="struts-default" &gt; 


       &lt;interceptors&gt; 

         &lt;interceptor-stack name="appDefault"&gt; 

            &lt;interceptor-ref name="timer" /&gt; 

            &lt;interceptor-ref name="logger" /&gt; 

            &lt;interceptor-ref name="defaultStack" /&gt; 

         &lt;/interceptor-stack&gt; 

        &lt;/interceptors&gt;          

        &lt;default-interceptor-ref name="appDefault" /&gt; 

       &lt;!-- rest of package omitted --&gt; 

&lt;/package&gt; 

</pre>
</div></div><p>In the code above we use the interceptors node to define a new stack of interceptors that includes the timer, logger, and defaultStack interceptors. We give this new interceptor stack a name of appDefault. Then we use the default-interceptor-ref node to specify that for all Actions defined inside this package node the appDefault stack of interceptors are to be used. Thus the timer and logger interceptor will be executed for each Action in this package.</p><p>Note that in both examples we are still executing all the other interceptors by including the defaultStack as one of the interceptor-ref nodes. When you specify what interceptors you want to use for an Action or a package then only those interceptors are executed. So if in the example we had left out the interceptor-ref for defaultStack only the logger and timer interceptors would have executed.</p><h3 id="IntroducingInterceptors-CreateYourOwnInterceptor">Create Your Own Interceptor</h3><p>In addition to specifying your own stack of interceptors, you can also write your own new interceptor and add it to the stack that is executed. The Struts <a shape="rect" href="writing-interceptors.html">Writing Interceptors</a> guide explains how to do this. For example, you could create your own interceptor to handle authentication and authorization.</p><h3 id="IntroducingInterceptors-Summary">Summary</h3><p>Interceptors provide the Struts 2 framework with both power and flexibility. Developers may add additional interceptors (either ones provided by Struts 2 or ones they create) to the stack of interceptors executed when an Action class is called.</p><p>For more information about interceptors consult the Struts 2 <a shape="rect" href="interceptors.html">Interceptor</a> documentation.</p></div>
        </div>

        
    </div>
</div>
<div class="footer">
    Generated by CXF SiteExporter
</div>
</body>
</html>
